<template>
  <el-dialog
    :title="$t('msg.user.title')"
    :model-value="modelValue"
    @close="closed"
    width="30%"
  >
    <el-input
      :placeholder="$t('msg.user.placeholder')"
      v-model="excelName"
    ></el-input>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closed">{{ $t('msg.user.close') }}</el-button>
        <el-button type="primary" :loading="loading" @click="onConfirm">{{
          $t('msg.user.confirm')
        }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { watchSwitchLang } from '@/utils/i18n'
import { getUserAll } from '@/api/user-manage'
import { USER_RELATIONS } from './Export2ExcelConstants'
import { dateFormat } from '@/utils/date'
defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }
})
const i18n = useI18n()
let exportDefaultName = i18n.t('msg.user.defaultName')
const excelName = ref('')
excelName.value = exportDefaultName
watchSwitchLang(() => {
  exportDefaultName = i18n.t('msg.user.defaultName')
  excelName.value = exportDefaultName
})

const emits = defineEmits('update:modelValue')
const closed = () => {
  emits('update:modelValue', false)
}
const loading = ref(false)
const onConfirm = async () => {
  loading.value = true
  const allUser = await getUserAll()
  const excel = await import('@/utils/Export2Excel')
  const data = formatJson(USER_RELATIONS, allUser)
  excel.export_json_to_excel({
    header: Object.keys(USER_RELATIONS),
    data,
    filename: excelName.value || exportDefaultName
  })
  closed()
}

const formatJson = (headers, rows) => {
  return rows.map((item) => {
    return Object.keys(headers).map((key) => {
      // 时间特殊处理
      if (headers[key] === 'createTime') {
        return dateFormat(item[headers[key]])
      }
      if (headers[key] === 'role') {
        const rolesStr = item[headers[key]]
        const roles = JSON.parse(rolesStr)
        return JSON.stringify(roles.map((role) => role.title))
      }
      return item[headers[key]]
    })
  })
}
</script>

<style lang="scss" scoped></style>
